package common.exception;

import common.model.result.Result;
import common.model.result.ResultCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 异常处理工具类
 */
public class ExceptionHandlerUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerUtil.class);
    
    /**
     * 处理空指针异常
     */
    public static Result handleNullPointerException(NullPointerException e) {
        logger.error("发生空指针异常: ", e);
        return Result.failure(ResultCodeEnum.INTERNAL_SERVER_ERROR, "系统发生空指针异常，请联系管理员");
    }
    
    /**
     * 处理业务异常
     */
    public static Result handleBusinessException(BusinessException e) {
        logger.warn("业务异常: {}", e.getMessage());
        return Result.failure(e.getResultCode(), e.getMessage());
    }
    
    /**
     * 处理非法参数异常
     */
    public static Result handleIllegalArgumentException(IllegalArgumentException e) {
        logger.warn("非法参数: {}", e.getMessage());
        return Result.failure(ResultCodeEnum.BAD_REQUEST, e.getMessage());
    }
    
    /**
     * 处理所有其他异常
     */
    public static Result handleException(Exception e) {
        logger.error("系统异常: ", e);
        return Result.failure(ResultCodeEnum.INTERNAL_SERVER_ERROR, "系统繁忙，请稍后再试");
    }
    
    /**
     * 安全执行代码块，捕获并处理异常
     * @param action 要执行的代码块
     * @return 执行结果或异常处理结果
     */
    public static Result safeExecute(ExceptionAction action) {
        try {
            return action.execute();
        } catch (NullPointerException e) {
            return handleNullPointerException(e);
        } catch (BusinessException e) {
            return handleBusinessException(e);
        } catch (IllegalArgumentException e) {
            return handleIllegalArgumentException(e);
        } catch (Exception e) {
            return handleException(e);
        }
    }
    
    /**
     * 函数式接口，用于传递执行代码块
     */
    @FunctionalInterface
    public interface ExceptionAction {
        Result execute() throws Exception;
    }
} 